package cn.benma666.kettle.yxjk;

import cn.benma666.myutils.HttpUtil;
import cn.benma666.myutils.StringUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.pentaho.di.trans.TransMeta;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 应用监控
 * @date 2019年1月14日上午10:25:23
 */
public class Appjk extends YxjkRunBase{
	private static final String QUERYYY_BYID_SQL = "通过id查询应用配置信息";
	private static final String PARAMS_CODE = "访问成功返回码";
	private static final String PARAMS_READTIME = "超时时间（毫秒）";
	private static final String PARAMS_TIMES = "重新请求次数";

    @Override
	public JkResult test(Object[] outputRow) {
    	String jtrwid = outputRow[getFieldIndex(JKRW_JTRW)].toString();//具体任务id
    	String code = outputRow[getFieldIndex(JKRW_RWDJ)].toString();//任务等级，对应消息级别
    	//应用配置信息对象
    	JSONObject appObj = YxjkInit.jkdb.findFirst(configInfo.getString(QUERYYY_BYID_SQL), jtrwid);
    	if(appObj == null){
			return JkResult.error("监控任务【"+outputRow[getFieldIndex(JKRW_RWMC)]+"】的具体任务不存在！请重新配置此监控",code,JkConstants.YCLX_007);
    	}
    	String url = appObj.getString("dz");
    	String param = "";
    	String result = null;
        JSONObject repHeard = new JSONObject();
    	try {
    	    //10秒没有返回数据就认为异常
            result = HttpUtil.doStr(url, param,
                    HttpUtil.DEFAULT_QQBM,configInfo.getIntValue(PARAMS_READTIME),null,repHeard);
		} catch (Exception e) {
			ku.logBasic("检测到应用："+url+"访问异常",e);
			boolean flag = true;
			for(int i=1; i<=configInfo.getIntValue(PARAMS_TIMES);i++){
				try {
		            //10秒没有返回数据就认为异常
		            result = HttpUtil.doStr(url, param,
							HttpUtil.DEFAULT_QQBM,configInfo.getIntValue(PARAMS_READTIME),null,repHeard);
					flag = false;
					break;
				} catch (Exception e1) {
					ku.logBasic("重新第"+i+"次请求应用，检测到应用："+url+"访问异常",e);
				}
			}
			if(flag){
				return JkResult.error("监测到应用异常：" + e.getMessage(),code,JkConstants.YCLX_009);
			}
		}
    	String regEx = appObj.getString("jcgjz");//此处使用正则表达式匹配
    	if(StringUtil.isNotBlank(regEx)){
    		if(!regExMatcher(regEx,result)){
        		//应用访问异常
        		return JkResult.error("监测到应用异常:" + result,code,JkConstants.YCLX_009);
        	}
    	}else{
    		if(!configInfo.getString(PARAMS_CODE).contains(repHeard.getString("status"))){
    			//应用访问异常
        		return JkResult.error("监测到应用异常:[" + repHeard.getString("status") + "]" + result,code,JkConstants.YCLX_009);
    		}
    	}
		return JkResult.success("",code);
	}

	/**
     * 正则表达式匹配
     * @param regEx 正则
     * @param str 匹配的字符串
     * @return boolean
     */
    private boolean regExMatcher(String regEx,String str){
    	boolean flag = true;
    	try {
    		Pattern pattern = Pattern.compile(regEx);
        	// 忽略大小写的写法
            // Pattern pattern = Pattern.compile(regEx, Pattern.CASE_INSENSITIVE);
        	Matcher matcher = pattern.matcher(str);
            // 查找字符串中是否有匹配正则表达式的字符/字符串
            flag = matcher.find();
		} catch (Exception e) {
			flag = false;
			ku.logBasic("--->应用监控中配置的正则表达式：" + regEx + "有误，请重新配置此正则！", e);
		}
        return flag;
    }

    @Override
	public String getDefaultConfigInfo(TransMeta transMeta, String stepName) throws Exception {
		//创建一个JSON对象，用于构建配置对象，避免直接拼字符串构建JSON字符串
        JSONObject params = new JSONObject();
        params.put(QUERYYY_BYID_SQL, "select * from SYS_QX_APP where id = ?");
        params.put(PARAMS_CODE, "200、302");
        params.put(PARAMS_READTIME, "10000");
        params.put(PARAMS_TIMES, "3");
		return JSON.toJSONString(params, true);
	}



}
